﻿using Mitek.Web.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Mitek.Web.App_Start
{
    public class SessionContext
    {
        /// <summary>
        /// 当前登陆用户
        /// </summary>
        public static ApplicationUser CurrentUser
        {
            get
            {
                AutoSyncIdentity();
                return HttpContext.Current.Session["CURRENT_USER"] as ViewModels.ApplicationUser;
            }
            set
            {
                HttpContext.Current.Session["CURRENT_USER"] = value;
            }
        }

        /// <summary>
        /// 以Cookies为准，若Cookies为空而Session不为空，则自动注销Session
        /// 若Cookies不为空，而Session为空则自动登录
        /// 如二则都不为空或者二者都为空，则不做任何处理
        /// </summary>
        public static void AutoSyncIdentity()
        {
            var currentUser = HttpContext.Current.Session["CURRENT_USER"] as ViewModels.ApplicationUser;
            // 而Form Auth Cookies为空，则自动注销;
            if (!HttpContext.Current.User.Identity.IsAuthenticated && currentUser != null)
                SessionContext.SignOut();

            // Don't use SessionContext.CurrentUser in this function, because we called "AutoLoginByCookies" in Session.CurrentUser's getter.
            // 若Cookies不为空，而Session为空，则通过Cookies重新登录;
            if (HttpContext.Current.User.Identity.IsAuthenticated && currentUser == null)
            {
                var userService = DependencyResolver.Current.GetService<Mitek.Services.Auth.IUserService>();
                var account = userService.Get(Convert.ToInt32(HttpContext.Current.User.Identity.Name));
                var user = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<Mitek.Models.Auth.User, ViewModels.ApplicationUser>().Map(account);
                if (user != null)
                    SessionContext.SignIn(user);
            }
        }

        public static string DisplayName
        {
            get
            {
                if (CurrentUser == null)
                    return String.Empty;
                if (!String.IsNullOrEmpty(CurrentUser.Name))
                    return CurrentUser.Name;
                return CurrentUser.Email;
            }
        }

        public static bool IsAuthenticated
        {
            get
            {
                AutoSyncIdentity();
                return HttpContext.Current.User.Identity.IsAuthenticated;
            }
        }

        #region 登陆、注销
        public static void SignOut()
        {
            HttpContext.Current.Session.Remove("CURRENT_USER");
            FormsAuthentication.SignOut();
        }
        public static void SignIn(ViewModels.ApplicationUser user)
        {
            SignOut();
            FormsAuthentication.SetAuthCookie(user.ID.ToString(), true);

            var userService = DependencyResolver.Current.GetService<Mitek.Services.Auth.IUserService>();
            //var userRoles = userService.GetUserRoles();
            user.Role = userService.GetUserByID(user.ID).RoleID;
            SessionContext.CurrentUser = user;
        }
        #endregion
    }
}